#include <iostream>
#include <memory>
#include <ostream>
#include <vector>

using std::cout;
using std::endl;
using std::shared_ptr;
using std::vector;

class Point
{
public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {
        cout << "Point(int = 0, int = 0)" << endl;
    }

    void print() const
    {
        cout <<"(" << _ix
             << ", " << _iy
             << ")" << endl;
    }

    ~Point()
    {
        cout << "~Point()" << endl;
    }

    friend std::ostream &operator<<(std::ostream &os, const Point &rhs);
private:
    int _ix;
    int _iy;
};

std::ostream &operator<<(std::ostream &os, const Point &rhs)
{
    os <<"(" << rhs._ix
       << ", " << rhs._iy
       << ")";

    return os;

}
void test()
{
    shared_ptr<Point> sp(new Point(10, 20));
    cout << "*sp = " << *sp << endl;
    cout << "sp.get() = " << sp.get() << endl;
    cout << "sp.use_count() = " << sp.use_count() << endl;

    cout << endl << endl;
    shared_ptr<Point> sp2(sp);//ok,复制
    cout << "*sp = " << *sp << endl;
    cout << "*sp2 = " << *sp2 << endl;
    cout << "sp.get() = " << sp.get() << endl;
    cout << "sp2.get() = " << sp2.get() << endl;
    cout << "sp.use_count() = " << sp.use_count() << endl;
    cout << "sp2.use_count() = " << sp2.use_count() << endl;

    cout << endl;
    shared_ptr<Point> sp3(new Point(30, 100));
    cout << "*sp3 = " << *sp3 << endl;
    cout << "sp3.get() = " << sp3.get() << endl;
    cout << "sp3.use_count() = " << sp3.use_count() << endl;

    cout << endl;
    sp3 = sp;//ok, 赋值
    cout << "*sp = " << *sp << endl;
    cout << "*sp2 = " << *sp2 << endl;
    cout << "*sp3 = " << *sp3 << endl;
    cout << "sp.get() = " << sp.get() << endl;
    cout << "sp2.get() = " << sp2.get() << endl;
    cout << "sp3.get() = " << sp3.get() << endl;
    cout << "sp.use_count() = " << sp.use_count() << endl;
    cout << "sp2.use_count() = " << sp2.use_count() << endl;
    cout << "sp3.use_count() = " << sp3.use_count() << endl;

    cout << endl << "移动语义" << endl;
    shared_ptr<Point> sp4(std::move(sp));//移动构造函数
    cout << "*sp4 = " << *sp4 << endl;
    cout << "sp4.get() = " << sp4.get() << endl;
    cout << "sp4.use_count() = " << sp4.use_count() << endl;

    cout << endl;
    sp4 = std::move(sp3);//移动赋值函数
    cout << "*sp4 = " << *sp4 << endl;
    cout << "sp4.get() = " << sp4.get() << endl;
    cout << "sp4.use_count() = " << sp4.use_count() << endl;

    cout << endl << "作为容器元素" << endl;
    vector<shared_ptr<Point>> vec;
    /* vec.push_back(shared_ptr<int>(new Point(1000, 1000))); */
    /* cout << "=== " <<  *vec[0] << endl; */
    //因为shared_ptr具备移动语义以及值语义，所以作为容器元素
    //的时候，既可以传递左值，也可以传递右值
    vec.push_back(sp4);//将sp4拷贝到vector
    vec.push_back(std::move(sp4));
    cout << "=== " <<  *vec[0] << endl;
    cout << "2222" << endl;
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

